#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QFileDialog>
#include <QTextStream>
#include <QSaveFile>
#include <QtGlobal>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QUrl>
#include <QDebug>
#include <QDesktopServices>
#include "globalprofile.h"
#include "aboutdialog.h"
#include "downloadffmpegdialog.h"
#include "usescriptdialog.h"


MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{
  ui->setupUi(this);
  ui->statusBar->setVisible(false);

#ifdef Q_OS_DARWIN
  this->setUnifiedTitleAndToolBarOnMac(true);
#endif

  fileListModel = new FileListModel();
  ui->fileListView->setModel(fileListModel);

  scriptEditor = new ScriptEditor();

  connect(ui->actionOpenFiles, &QAction::triggered, this, &MainWindow::openFiles);
  connect(ui->actionRemoveSelectedFiles, &QAction::triggered, this, &MainWindow::removeSelectedFiles);
  connect(ui->actionRemoveAllFiles, &QAction::triggered, this, &MainWindow::removeAllFiles);
  connect(ui->actionExportScript, &QAction::triggered, this, &MainWindow::exportScript);
  connect(ui->actionRemoveIllegalFiles, &QAction::triggered, this, &MainWindow::removeIllegalFiles);
  connect(ui->actionOpenConfigFolder, &QAction::triggered, this, &MainWindow::openConfigFolder);
  connect(ui->actionResetSetters, &QAction::triggered, ui->setterBox, &SetterBox::resetSettings);

  connect(ui->actionAboutQt, &QAction::triggered, this, &MainWindow::aboutQt);
  connect(ui->actionAboutMe, &QAction::triggered, this, &MainWindow::aboutMe);
  connect(ui->actionDownloadFFmpeg, &QAction::triggered, this, &MainWindow::downloadFFmpeg);
  connect(ui->actionHowToUse, &QAction::triggered, this, &MainWindow::howToUseScript);

  connect(ui->actionShowAdvancedEditor, &QAction::triggered, scriptEditor, &ScriptEditor::show);

  setupEditor();
}

MainWindow::~MainWindow()
{
  if (scriptEditor != nullptr)
    scriptEditor->deleteLater();
  delete ui;
}

void MainWindow::setupEditor()
{

  connect(this->scriptEditor, &ScriptEditor::requireLines, [ = ]() {
    scriptEditor->acceptLines(this->genScriptLines());
  });
  qDebug() << "scriptEditor setted up.";
}


QStringList MainWindow::genScriptLines()
{
  QStringList scriptLines;
  QStringList fileList = fileListModel->fileList();
  foreach (QString path, fileList) {
    scriptLines << ui->setterBox->fullLine(path);
  }
  return scriptLines;
}


void MainWindow::exportScript()
{
  if (! ui->setterBox->checkFields())
    return;
  QStringList scriptLines;

#ifdef Q_OS_UNIX
  scriptLines << "#!/bin/sh"
              << "#Generated by FFFever";
#endif
  scriptLines << genScriptLines();
  foreach (QString s, scriptLines) {
    qDebug() << s;
  }

#ifdef Q_OS_WIN
  QString filterStr = tr("批处理文件(*.bat);;所有文件(*.*)");
#else
  QString filterStr = tr("Bash脚本(*.sh);;所有文件(*.*)");
#endif

  QString outFileName = QFileDialog::getSaveFileName(this, tr("保存脚本"), QDir::homePath(), filterStr);

  QFileInfo info(outFileName);

#ifdef Q_OS_WIN
  if (info.suffix() != "bat")
    outFileName = outFileName + ".bat";
#else
  if (info.suffix() != "sh")
    outFileName = outFileName + ".sh";
#endif

  qDebug() << outFileName;

  QSaveFile outFile(outFileName);
  if (outFile.open(QFile::WriteOnly | QFile::Truncate)) {
    QTextStream outStream(&outFile);
    foreach (QString s, scriptLines)
      outStream << s << endl;
//    outFile.setPermissions(QFileDevice::ExeOther | QFileDevice::ExeOwner | QFileDevice::ExeUser);
  }
  outFile.commit();

}


void MainWindow::popMsg(QString s)
{
  ui->statusBar->showMessage(s);
}


void MainWindow::openFiles()
{
  QStringList openedFiles = QFileDialog::getOpenFileNames(this, tr("选择需要转码的文件"), QDir::homePath());
  if (! openedFiles.isEmpty()) {
    fileListModel->appendFiles(openedFiles);
    popMsg(tr("已导入%1个文件。").arg(openedFiles.size()));
  }
}

void MainWindow::removeSelectedFiles()
{
  QModelIndexList selected = ui->fileListView->selectionModel()->selectedIndexes();
  fileListModel->removeByIndexes(selected);
  popMsg(tr("已删除选定的文件。"));
}

void MainWindow::removeAllFiles()
{
  fileListModel->clearAll();
  popMsg(tr("已删除所有文件。"));
}

void MainWindow::removeIllegalFiles()
{
  fileListModel->autoRemoveIllegalFiles();
  popMsg(tr("非法文件已移除。"));
}

void MainWindow::openConfigFolder()
{
  QString path = GlobalProfile::configDir() + "/";
  QFileInfo fi(path);
  QDesktopServices::openUrl(QUrl::fromLocalFile(fi.absolutePath()));
  qDebug() << "打开配置文件目录";
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
  if (event->mimeData()->hasUrls())
    event->acceptProposedAction();
}

void MainWindow::dropEvent(QDropEvent *event)
{
  QList<QUrl> list = event->mimeData()->urls();
  if (list.isEmpty())
    return;

  QStringList fList;

  foreach (QUrl u, list)
    fList << u.toLocalFile();

  fileListModel->appendFiles(fList);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
  ui->setterBox->saveSettings();
  event->accept();
}

void MainWindow::aboutQt()
{
  QApplication::aboutQt();
}

void MainWindow::aboutMe()
{
  AboutDialog::showMe(this);
}

void MainWindow::downloadFFmpeg()
{
  DownloadFFMPEGDialog *d = new DownloadFFMPEGDialog(this);
  d->exec();
}

void MainWindow::howToUseScript()
{
  UseScriptDialog *d = new UseScriptDialog(this);
  d->exec();
}


